package com.dbflow5.processor.utils;

import com.dbflow5.processor.ProcessorManager;
import com.dbflow5.processor.definition.BaseDefinition;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;

import java.io.IOException;
import java.util.function.Function;

public class WriterUtils{
    public static boolean writeBaseDefinition(BaseDefinition baseDefinition, ProcessorManager processorManager) {
        boolean success = false;
        try {
            javaFile(baseDefinition.packageName, builder -> builder, unused -> baseDefinition.typeSpec())
                .writeTo(processorManager.processingEnvironment.getFiler());
            success = true;
        } catch (IOException e) {
            // ignored
        } catch (IllegalStateException i) {
            processorManager.logError(baseDefinition.getClass(), "Found error for class: $elementName");
            processorManager.logError(baseDefinition.getClass(), i.getMessage());
        }

        return success;
    }

    private static JavaFile javaFile(String packageName, Function<JavaFile.Builder, JavaFile.Builder> imports, Function<Void, TypeSpec> function) {
        JavaFile.Builder builder = JavaFile.builder(packageName, function.apply(null));
        builder = imports.apply(builder);
        return builder.build();
    }
}